package aws;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.UUID;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;

import play.Logger;
import play.libs.WS;
import play.libs.WS.WSRequest;
import utils.Constant;

public class AWSUtil {

    public static File fetchFile(String bucketName,String dir,String fileName){
        AWSCredentials credentials = new BasicAWSCredentials(Constant.AWS_ACCESS_KEY,Constant.AWS_SECRET_KEY);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTP);
        clientConfig.setConnectionTimeout(60000);
        AmazonS3 conn = new AmazonS3Client(credentials,clientConfig);
        InputStream is = conn.getObject(new GetObjectRequest(bucketName,dir+fileName)).getObjectContent();
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile("uc_",".wav");
            Files.copy(is, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            tmpFile.deleteOnExit();
        } catch (IOException e) {
            Logger.error(e, "[%s]->[%s] Fetch wav from AWS S3 failed!",bucketName,fileName);
        }finally{
            
        }
        Logger.info("[%s]: bucketName<%s>, fileName<%s>, file<%s>", "fetchFile",bucketName,fileName,tmpFile);
        return tmpFile;
    }
    
    
   
}
